from flask_records.decorators import query_by_page, query
from common.utils.utils import custom_marshal_pagination

GET_BY_PAGE_SQL = """
select *
from purchase_order
where (is_active = :is_active or :is_active is null)
  and (
            lower(purchase_order.notes) like lower(:search_str_re) or
            lower(purchase_order.order_sn) like lower(:search_str_re) or
            :search_str_re is null
    )   
  and (status = :status or :status is null)
  and (draft_status = :draft_status or :draft_status is null)
  and (purchase_order.date >= :date_begin or :date_begin is null)
  and (to_char(purchase_order.date, 'yyyy-MM-dd') <= :date_end or :date_end is null)    
  and (customer_id = :customer_id or :customer_id is null)
  and (warehouse_id = :warehouse_id or :warehouse_id is null)
"""


def get_by_page(page, page_size, sorted_by, sorted_by_type, search_str, **kwargs):
    sql = GET_BY_PAGE_SQL
    order_by_sql = "{} ORDER BY {} {}".format(sql, sorted_by, sorted_by_type)

    if search_str:
        # 以空格分割，搜索所有包含的
        search_str_re = '%{}%'.format('%'.join(search_str.split(" ")))
    else:
        search_str_re = None

    @query_by_page(order_by_sql, page_size=page_size)
    def _get_by_pagination(
            page, search_str_re, status=None, draft_status=None,
            date_begin=None, date_end=None, customer_id=None, warehouse_id=None,
            is_active=None, **kwargs):
        pass

    pagination = _get_by_pagination(
        page, search_str_re, **kwargs
    )
    pagination = custom_marshal_pagination(pagination)
    return pagination
